<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/*******************
***  wish订单同步处理
***  
*** 2017/06/3
**********/
class WishdataPro
{
	
	function __construct()
	{    
		 $this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
       $this->CI->load->library('Amazondata');
       $this->amazondata=new amazondata();
	}



//第一步先请取生成下载链接30
public function requestdownloadjob()
{
	//先读取当前已经授权的wish店铺，并存入db_wish_download表
	$wisharr=$this->db1->get_where("d_shop","platfromname='Wish' and agent_visit = 0")->result_array();
	foreach ($wisharr as $value) {
	if (empty($value['amazonkey'])) continue;
	
	 $shopname=$value['name'];
	 $shopid=$value['id'];
	 $this->refreshtoken($value['amazonkey'],$shopid);
	 $amazonkey=json_decode($value['amazonkey'],true);
	
     $token=$amazonkey[0]['access_token'];

     if(empty($token))continue;
     $isinfo= $this->db1->get_where("db_wish_download","shopid='{$shopid}'")->result_array();
     if (count($isinfo)==1) {
		$d="";
     	$d['token']=$token;

     	$this->db1->where('shopid',$shopid);
        $this->db1->update('db_wish_download',$d);
        continue;
     }

	 $d="";
     $d['shopname']=$shopname;
     $d['shopid']=$shopid;
     $d['token']=urlencode($token);
     $this->db1->insert('db_wish_download', $d);
	}



	//存入授权店铺结束
	$shoplist = $this->db1->get_where("db_wish_download","yz=0")->result_array();
	date_default_timezone_set('UTC');
	$start = date("Y-m-d",time()-3*24*3600).'T'.date("H:i:s",time()-3*24*3600);
	$end = date("Y-m-d",time()).'T'.date("H:i:s",time()-1*3600);
	
		$times = time() -6*86400;
		$start = gmdate("Y-m-d\TH:i:s",$times);
		$end = gmdate("Y-m-d\TH:i:s",time()-1*3600);
		
	
//			$cvalue = strtotime("2017-11-01 00:00:00");
//			$start = gmdate("Y-m-d\TH:i:s",$cvalue);
//			$end =  gmdate("Y-m-d\TH:i:s",time()-600);

	foreach($shoplist as $key=>$rsshop)
	{
	$url = sprintf("https://merchant.wish.com/api/v2/order/create-download-job?access_token=%s&start=%s&end=%s&format=json",$rsshop["token"], $start, $end);
	$context = stream_context_create(array( 'http' => array( 'method'=> 'POST',  'ignore_errors' => true, ),));
	$responsest = file_get_contents($url, TRUE, $context);
	$response=json_decode($responsest,true);
	if($response["code"]>0)
	{
		$responsejson=json_encode($response);
		$this->db1->update("db_wish_download",array("code"=>$response["code"],"dataurl"=>'',"data"=>$responsejson),"id='".$rsshop["id"]."'");	//存错误信息
		continue;
	}
	$job_id=$response['data']['job_id'];
	$pUrl = sprintf(
    "https://merchant.wish.com/api/v2/order/get-download-job-status?access_token=%s&job_id=%s&format=json",
    $access_token, $job_id);
	$this->db1->update("db_wish_download",array("job_id"=>$job_id,"start"=>$start,"end"=>$end,"url"=>$pUrl),"id='".$rsshop["id"]."'");
	}

	
	

}

//第二步定时循环刚才生成的请求连接 执行完第一步后，隔十分钟再执行seconddownloadjob
public function seconddownloadjob()
{
	$shoplist = $this->db1->get_where("db_wish_download","yz=0")->result_array();
	foreach($shoplist as $key=>$rsshop)
	{
		$urld = sprintf("https://merchant.wish.com/api/v2/order/get-download-job-status?access_token=%s&job_id=%s&format=json", $rsshop["token"], $rsshop["job_id"]);
		$contextd = stream_context_create(array('http' => array('method'=> 'POST','ignore_errors' => true, ),));
		$responseddata = file_get_contents($urld, TRUE, $contextd);
		$responsed=json_decode($responseddata,true);
		print_r($responsed);
		$status=strtolower($responsed['data']['status']);
		if($responsed["code"]==0)
		{
			if($status=='finished')
			{
				$file=$responsed['data']['download_link'];
				$this->db1->update("db_wish_download",array("code"=>0,"dataurl"=>$file,"data"=>$responseddata),"id='".$rsshop["id"]."'");
			}
		}else{
			$this->db1->update("db_wish_download",array("code"=>$responsed["code"],"dataurl"=>'',"data"=>$responseddata),"id='".$rsshop["id"]."'");	//存错误信息
		}
		
	}
	//可以定时执行或者直接执行
	$this->thirdstep();
}

public function thirdstep(){
	
	$dir = dirname(__FILE__) . "/../../uploads/Wish/";
	$dir2= date("Ymd");
	!is_dir($dir.$dir2) && @mkdir($dir.$dir2, 0755, true);
	$shoplist = $this->db1->get_where("db_wish_download"," code = 0 AND yz=0")->result_array();
	foreach($shoplist as $key=>$rsshop)
	{
		$file=$rsshop['dataurl'];
		$name = $rsshop["shopname"]."-".time()."-order.csv";
		$Path = $dir.$dir2. "/".$name;
		if($file){
			$content=file_get_contents($file);//下载到内存
			file_put_contents($Path, $content);
			$fileurl = $dir2. "/".$name;
			$this->db1->update("db_wish_download",array("file"=>$fileurl),"id='".$rsshop["id"]."'");	//存文件
		}
	}


	//可以定时执行或者直接执行
	$this->fourthstep();
}

public function fourthstep()
{
	setlocale(LC_ALL, 'en_US.UTF-8');
	$dir = dirname(__FILE__) . "/../../uploads/Wish/";
	$shoplist = $this->db1->get_where("db_wish_download"," yz=0 AND  `file`!=''")->result_array();
	foreach($shoplist as $key=>$rsshop)
	{
		$goods_list = array();
		$fileName = $rsshop["file"];
	
		if(!file_exists($dir.$fileName))	//文件不存在
		{
			continue;
		}
		
	
		// $file=file_get_contents($dir.$fileName);
  //      // $filearr= explode('\t', $file);
  //      print_r($file);

			$file = fopen($dir.$fileName,'r'); 
		$i = 0;
		while ($data = fgetcsv($file)) { //每次读取CSV里面的一行内容

			if($i>0){
		
			$goods_list[] = $data;
			}
			$i++;
		 }
         
		
		 if(count($goods_list)==0)	//文件没有内容
		 {
			continue;
		 }
	
		foreach($goods_list as $key=>$info)
		{

			$rorder = $this->db1->get_where("db_order_list","tradeid='".$info["1"]."' AND shopid='".$rsshop["shopid"]."'")->result_array();	//存在订单，不再更新
			if($rorder[0]["order_id"])
			{
				continue;
			}
			if ($info['3']!='APPROVED') {	//非此状态不更新
				continue;
			}
			$postdata="";
			$postdata["order_sn"] = $this->amazondata->getNo('wish');
			$postdata["dates"] = date("Y-m-d");
			$postdata["order_status"] =2;
			$postdata["order_source"] ='正常订单';
			$postdata['shipping_status']=0;
			$postdata["customerid"] =addslashes(trim($info['28']));
			$postdata["consignee"] =addslashes(trim($info['28']));
			$country=$this->checkcountry($info['36']);
			$postdata["country"] = $country;
			
			$rscountry = $this->db1->get_where("d_chinaexpress","NAME='".$country."'")->result_array();
			if($rscountry[0]["id"]){
				$postdata["country_cn"] = $rscountry[0]["FILED1"];
			}

			$postdata["province"] = addslashes(trim($info['34']));
			$postdata["city"] = addslashes(trim($info['33']));
				$address=addslashes(trim($info['31'])).','.addslashes(trim($info['32']));
				if (substr($address,0,1)==',') {
					$address=substr($address,1);
				}
				$addresslen=strlen($address)-1;
				if (substr($address,$addresslen)==',') {
				   $address=substr($address, 0,$addresslen);
				}
			$postdata["address"] =$address;
			// $postdata["address2"] = '';
			$postdata["zipcode"] = $info['35'];
			//$postdata["tel"] = $info['37']?$info['37']:0;
			$postdata["mobile"] = $info['38'];
			$postdata["country_code"] = $info['39'];
			$postdata["email"] = '';
			$postdata["shopid"] = $rsshop["shopid"];
			$rshop = $this->db1->get_where("d_shop","id=".$rsshop["shopid"])->result_array();
			$postdata["shopname"] = $rshop[0]["name"];
			$postdata["shopoper"] = $rshop[0]["updateoper"];
			$exchange=$this->db1->get_where("d_moneyrate","name='USD'")->result_array();
			$exchangerate=$exchange[0]["rate"]; 
			$postdata["moneytype"] ='USD';
			$postdata["tradeid"] = $info["1"];
			$postdata["goods_originask"] = substr($info["11"],1)*$info["15"];
			$postdata["goods_amount"] =substr($info["11"],1)*$info["15"]*$exchangerate;
			$postdata["shipping_fee"] = substr($info["13"],1)*$exchangerate;
			$postdata["shipping_originask"] = substr($info["13"],1);
			$postdata["add_time"] = time();
			$postdata["ordertime"] = $info["0"];
			$postdata["payid"] = $info["2"];
			$postdata["saleschannel"] = 'wish';
			
			if($rshop[0]["shop_platform_fee"]>0)
			{
				$shop_platform_fee  =$rshop[0]["shop_platform_fee"];
			}else{
				$shop_platform_fee = 0.15;
			}
			if($rshop[0]["shop_pay_fee"]>0)
			{
				$shop_pay_fee  =$rshop[0]["shop_pay_fee"];
			}else{
				$shop_pay_fee = 0.015;
			}


			$postdata["pay_fee"] = substr($info["11"],1)*$info["15"]*$shop_pay_fee*$exchangerate;
			$postdata['pack_fee']='';
			$postdata["platform_fee"] = substr($info["11"],1)*$info["15"]*$shop_platform_fee*$exchangerate;
			$postdata["paypalmail"]='';
			$postdata['platformID']  = $rshop[0]['platfrom'];//平台
			$postdata['moneyrate']  = $exchangerate;//汇率
			// print_r($postdata);
			// continue;
			$this->db1->trans_begin();
			try{
				$this->db1->insert("db_order_list",$postdata);
				$orderID = $this->db1->insert_id();
				$weight = 0;
				unset($goods_name);
					$rgoods = $this->db1->get_where("db_goods","goods_sku='{$info["4"]}' or cognatelist like '%,{$info["4"]},%'")->result_array(); 
					if(empty($rgoods))
					{
						$Status=7;
						$goods_id = 0;
						$sweight = 0;
						$weight = 0;
						$goods_sn = $info["4"];
						$costprice = 0;
					}else{
						$factorycode = $this->factorycode();
						$Status=2;
						$goods_id = $rgoods[0]["goods_id"];
						$sweight = $info["15"] * $rgoods[0]["g_weight"];
						$weight = $weight+$sweight;
						$goods_sn = $rgoods[0]["goods_sku"];
						if(is_numeric($goods_sn) && preg_match('|^\d{8}$|',$goods_sn))	//数字并且8位SKU并且11 12开头
						{
							$goodscode  = substr($goods_sn,0,2);//取开头2位数
							if(in_array($goodscode,$factorycode))	//是否存在在工厂code
							{
								$costprice = $rgoods[0]["g_costprice"];	//定制衣服按成本价计算
							}
						}else{
							//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
							if(is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods[0]["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
							{
								$goodscodes  = substr($rgoods[0]["goods_parent_sku"],0,2);//取开头2位数
								if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
								{
									$costprice = $rgoods[0]["bulkprice"];	//批量按关联价计算
								}
							}else{
								$costprice = $rgoods[0]["g_costprice"];
							}
						}
						$goods_sn = $rgoods[0]["goods_sku"];
						$goods_name =  $rgoods[0]["goods_name"];
					}
					
					$postsell = "";
					$postsell["order_id"] = $orderID;
					$postsell["goods_id"] = $goods_id;
					$postsell["goods_name"] = $goods_name?$goods_name:addslashes($info["5"]);
					$postsell["goods_sn"] = $goods_sn;
					$postsell["costprice"] = $costprice;
					$postsell["goods_number"] = $info["15"];
					$postsell["goods_price"] = substr($info["11"],1)*$exchangerate;
					$postsell["goods_weight"]=$weight;
					$postsell["product_link"]=$info["7"];
					$postsell["goods_amount"] = substr($info["11"],1)*$info['15']*$exchangerate;
					$postsell["originsellprice"] = substr($info["11"],1);
					$postsell["originsku"] = $info["4"];
					$this->db1->insert("db_order_sell",$postsell);
					if($goods_id==0)
					{
						$this->db1->update("db_order_list",array("order_status"=>7),"order_id=".$orderID);
					}
					if($weight)
					{
						$this->db1->update("db_order_list",array("orderweight"=>$weight),"order_id=".$orderID);
					}
				// }
 //更新日志
				$imgdata["goods_id"] = $orderID;	//订单ID
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'wish接口自动新增订单,交易ID='.$info["2"];
				$imgdata["createUser"] ='auto';
				$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));
				$this->db1->trans_commit();
			}catch (Exception $e){
				$this->db1->trans_rollback();
				$msg =  $e->getMessage();
				print_r($msg);exit;
			}



		}
				//保存退货信息
		foreach($goods_list as $key=>$info)
		{
			$rorder = $this->db1->get_where("db_wish_refund","tradeid='".$info["1"]."' AND shopid='".$rsshop["shopid"]."'")->result_array();
			$rshop = $this->db1->get_where("d_shop","id=".$rsshop["shopid"])->result_array();
			if($rorder[0]["order_number"])
			{
				continue;
			}
			if ($info['3']!='REFUNDED BY WISH FOR MERCHANT') {	//非此状态不更新
				continue;
			}
			
				$order=$this->db1->get_where("db_order_list","tradeid='".$info["1"]."'")->result_array();
			 if($order[0]["order_id"]>0){
				$exchangerate=$order[0]["moneyrate"]; 
				$postdata="";
				$postdata["order_number"] =$info["1"];
				$postdata["shopid"] = $rsshop["shopid"];
				$postdata["shopname"] =  $rshop[0]["name"];
				$postdata["moneytype"] ='USD';
				$postdata["tradeid"] = $info["1"];
				$postdata["add_time"] =time();
				
				$postdata["Refund_Responsibility"]= $info["39"];
				$postdata["Refund_Amount"]=$info["40"];
				$postdata["Refund_Date"]=$info["41"];
				$postdata["Refund_Reason"]=addslashes($info["42"]);

				$postdata['moneyrate']  = $exchangerate;//汇率
				$postdata["Refund_Amount_Rmb"] = $info["40"]*$exchangerate;
				$postdata["order_id"] =$order[0]["order_id"];
				$postdata["order_sn"] =$order[0]["order_sn"];
				$postdata["instime"] = time();
				$postdata["goods_sn"] =$info["4"];
				$rgoods = $this->db1->get_where("db_goods","goods_sku='".$info["4"]."' or cognatelist like '%,".$info["4"].",%'")->result_array(); 
				$postdata["goods_id"] =$rgoods[0]["goods_id"]?$rgoods[0]["goods_id"]:0;
				 $this->db1->insert("db_wish_refund",$postdata);


			}
		}
	




			//测试使用下面
			// $this->db1->update("db_wish_download",array("url"=>'',"job_id"=>'',"start"=>'',"end"=>'',"code"=>'',"dataurl"=>'',"data"=>'',"file"=>''),"id='".$rsshop["id"]."'");
				//正式使用下面
			$this->db1->update("db_wish_download",array("yz"=>1),"id='".$rsshop["id"]."'");	//是否执行完成

			$this->db1->delete("db_wish_download","yz='1'");		//直接删除已更新,有错误信息的保留，以备后查
		

		

	

		
	}

	echo "OK";
	die;
}

public function factorycode()
{
	$rsdb = $this->db1->get_where("db_factory","code >0")->result_array();
	foreach($rsdb as $key =>$rs)
	{
		$factorycode[] = $rs["code"];	//工厂编号
	}

	return $factorycode;
}


public function checkcountry($country){
if (strpos($country, '(Great Britain)')===false) {
return $country;
}

return substr($country,0,14);

}


public function refreshtoken($amazonkey1,$shopid){

	$amazonkeyarr=json_decode($amazonkey1,true);
	$expiry_time=$amazonkeyarr[0]['expiry_time'];

			if($expiry_time< time())	//过期了，需要重新获得token
		{

			$data=$amazonkeyarr;
			$client_secret=$data['wishsecret'];
			$refresh_token=$data[0]['refresh_token'];
			$client_id=$data[0]['client_id'];
			$url = sprintf("https://merchant.wish.com/api/v2/oauth/refresh_token?&client_id=%s&client_secret=%s&refresh_token=%s&grant_type=refresh_token",$client_id, $client_secret, $refresh_token);
			$context = stream_context_create(array(
			'http' => array(
			'method'        => 'POST',
			'ignore_errors' => true,
					),
				));

			$response = file_get_contents($url, TRUE, $context);
			$response=json_decode($response,true);
			//print_r($response);
			$access_token=$response['data']['access_token'];
			$refresh_token=$response['data']['refresh_token'];
			$expires_in=$response['data']['expires_in'];
			$expiry_time=$response['data']['expiry_time'];
			$data[0]['access_token']=$access_token;
			$data[0]['expires_in']=$expires_in;
			$data[0]['refresh_token']=$refresh_token;
			$data[0]['expiry_time']=$expiry_time;
			$damazonkey=json_encode($data);

			$token=$access_token;
			$sql="UPDATE d_shop SET amazonkey='".$damazonkey."' WHERE id='".$shopid."'";
			//echo $sql;
			$this->db1->query($sql);
				// print_r($sql);
	   //            exit;
		}
}










}


?>